package com.adxon.servlet;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.adxon.MsgException;
import com.adxon.cookie.Station;
import com.adxon.data.Base;
import com.adxon.data.Individual;
import com.adxon.data.Item;
import com.adxon.data.Link;
import com.adxon.data.Mark;
import com.adxon.data.Star;

@SuppressWarnings("serial")
public class StarServlet extends ServletBase{
	public void doGet(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		try{
			resp.setContentType("text/plain");
			String g=Base.regulate(req.getParameter("g"));
			String k=Base.regulate(req.getParameter("k"));
			if(g!=null || k!=null){
				int r=Integer.parseInt(req.getParameter("r"));
				Item u=Station.getCurrentUser(req);
				if(k!=null){
					Item i=(Item)new Item().update(new StringTokenizer(k,"."));
					int n=i.getKind();
					if(n==Individual.KN){
						if(!i.equals(u))
							follow(i.getId(),g,u.getId(),r);
					}else{
						if(!i.isOwnerEquals(u) || n==Link.KN){
							System.out.println("StarServlet: "+req.getRequestURI()+" - Mark="+k+'/'+r);
							Item f=i.getKind()==Mark.KN?i.getRef():i;
							i=new Mark();
							i.setOwner(u);
							i.setRef(f);
							try{
								i.update();
							}catch(MsgException e){
								f.addRef();
							}
						}else System.out.println("StarServlet: "+req.getRequestURI()+" - Rate="+k+'/'+r);
						i.setRate(r);
						i.setTime(0);
						i.commit();
					}
				}else follow(0,g,u.getId(),r);
				print(resp,"200 OK");
				return;
			}
		}catch(NumberFormatException e){
		}catch(MsgException e){}
		print(resp,"400 Bad Request");
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException,ServletException{
		doGet(req,resp);
	}
	private void follow(long id,String tags,long owner,int rate)throws MsgException{
		System.out.println("StarServlet: - Follow="+id+'/'+owner+'/'+tags+'/'+rate);
		Star f=new Star();
		f.setId(id);
		f.setOwner(owner);
		f.setRate(rate);
		f.setTags(tags);
		f.setTime(0);
		f.commit();
	}
}